import React, { useState } from 'react';
import { Upload, message, Button, Tooltip } from 'antd';
import { ExclamationCircleOutlined, UploadOutlined } from '@ant-design/icons';
import Modal from 'antd/lib/modal/Modal';
// import ErrorBook from '../ErrorBook/ErrorBook';

const maxSize = 1024 * 1024 * 20; // 20M

interface Props {
  onAfterSuccess?: () => void;
  url: string;
}

export default function UploadBtn(props: Props) {
  const [visible, setVisible] = useState(false);
  const [fileList, setFileList] = useState<any[]>([]);
  const [uploading, setUploading] = useState(false);

  const [errors, setErrors] = useState([]);

  const handleUpload = () => {
    const formData = new FormData();
    setUploading(true);
    fileList.forEach((file) => {
      formData.append('file', file);
    });
    // You can use any AJAX library you like
    fetch(props.url, {
      method: 'POST',
      body: formData,
    })
      .then((res) => res.json())
      .then((res: any) => {
        if (res.code === 0) {
          setFileList([]);
          setVisible(false);
          props.onAfterSuccess && props.onAfterSuccess();
          message.success('upload successfully.');
        } else {
          if (res.data && res.data.length) {
            setErrors(res.data);
          } else {
            message.error('upload failed.' + (res.msg || ''));
          }
        }
      })
      .catch(() => {
        message.error('upload failed.');
      })
      .finally(() => {
        setUploading(false);
      });
  };

  const uploadProps = {
    name: 'file',
    accept: '.xlsx,.csv',
    // action: '/core-symbol/STOCK/import',
    withCredentials: true,
    onRemove: () => {
      setFileList([]);
    },
    beforeUpload: (file: any) => {
      console.log(file);
      if (file.size > maxSize) {
        message.warning('Supports up to 20M files');
        return false;
      }
      setFileList([file]);
      return false;
    },
    // onChange(info: any) {
    //   if (info.file.status !== 'uploading') {
    //     console.log(info.file, info.fileList);
    //   }
    //   if (info.file.status === 'done') {
    //     message.success(`${info.file.name} file uploaded successfully`);
    //   } else if (info.file.status === 'error') {
    //     message.error(`${info.file.name} file upload failed.`);
    //   }
    // },
    fileList,
  };

  return (
    <div>
      <Button
        icon={<UploadOutlined />}
        onClick={() => {
          setVisible(true);
          setFileList([]);
        }}
      >
        Import
      </Button>
      <Modal
        title={
          <div>
            Import Modal
            <Tooltip title="After uploading successfully, it cannot be undone">
              <ExclamationCircleOutlined style={{ marginLeft: 6 }} />
            </Tooltip>
          </div>
        }
        visible={visible}
        okButtonProps={{
          disabled: !fileList.length,
          loading: uploading,
        }}
        okText="Start Upload"
        onOk={handleUpload}
        onCancel={() => {
          setVisible(false);
          setFileList([]);
        }}
        zIndex={1005} //
      >
        <Upload {...uploadProps}>
          <Button icon={<UploadOutlined />}>Import Excel</Button>
        </Upload>
        {/* <div style={{ marginTop: 6 }}>
          <Text type="secondary">Only supports .xlsx suffix files</Text>
        </div> */}
      </Modal>
      {/* <ErrorBook
        data={errors}
      /> */}
    </div>
  );
}
